package com.tencent.wxcloudrun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.utils.AesException;
import com.tencent.wxcloudrun.utils.WXBizMsgCrypt;
import me.chanjar.weixin.common.util.XmlUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/3/1 16:31
 * @description: TODO
 */
@RestController
public class MinProgrameRegistController {
    @Autowired
    private RestTemplate restTemplate;
    @PostMapping(value = "/regist")
    public String registMinPrograme(@RequestBody JSONObject json, HttpServletRequest request){
        /**
         * {
         *   "name": "tencent", // 企业名
         *   "code": "123", // 企业代码
         *   "code_type": 1, // 企业代码类型（1：统一社会信用代码， 2：组织机构代码，3：营业执照注册号）
         *   "legal_persona_wechat": "123", // 法人微信
         *   "legal_persona_name": "candy", // 法人姓名
         *   "component_phone": "1234567" //第三方联系电话
         * }
         */
        String component_access_token = getComponent_access_token();
        String url = "https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token="+component_access_token;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String toString = json.toString();
        HttpEntity requestEntity = new HttpEntity(toString, headers);
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, new Object[0]);
        String body = entity.getBody();
        JSONObject object = JSON.parseObject(body);
        String errcode = object.getString("errcode");
        System.out.println(errcode);
        return errcode;
    }

    private String getComponent_access_token(){

        String url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
        String component_appid= "wx2fb98bf98531eaba";
        String component_appsecret= "4bf491d78c838e668c879b2f69b919cf";
        String component_verify_ticket = "lichongbingyueling";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("component_appid", component_appid);
        jsonObject.put("component_appsecret",component_appsecret);
        jsonObject.put("component_verify_ticket",component_verify_ticket);
        String toString = jsonObject.toString();
        HttpEntity requestEntity = new HttpEntity(toString, headers);
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, new Object[0]);
        String body = entity.getBody();
        JSONObject object = JSON.parseObject(body);
        String component_access_token = object.getString("component_access_token");
        return component_access_token;
    }

    @PostMapping(value = "/callback")
    public String callback(HttpServletRequest request, HttpServletResponse response) throws IOException, AesException {
        request.setCharacterEncoding("UTF-8");

        response.setCharacterEncoding("UTF-8");
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        String s = request.getParameter("s");
        System.out.println(s);
        // 从请求中读取整个post数据
        InputStream inputStream = request.getInputStream();
        String postData = IOUtils.toString(inputStream, "UTF-8");
        String token = "owzdntuxaycwigdxykntmleupp";
        String aeskey= "oidyqp17u4syhmwhf8e6yyramlkqesopti7g5qud5nb";
        String appid = "wx2fb98bf98531eaba";
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, aeskey, appid);
        String xml = pc.decryptMsg(msg_signature, timestamp, nonce, postData);
        System.out.println(xml);
        Map<String, Object> xml2Map = XmlUtils.xml2Map(xml);
        System.out.println(xml2Map);
        return "success";
    }
    /**
     * mall.yuelingnet.cn/index.php?s=/task/wechat/callback/appid/$APPID$
     */
    @PostMapping(value = "/index.php")
    public String message(HttpServletRequest request, HttpServletResponse response) throws IOException, AesException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        String s = request.getParameter("s");
        System.out.println(s);
        // 从请求中读取整个post数据
        InputStream inputStream = request.getInputStream();
        String postData = IOUtils.toString(inputStream, "UTF-8");
        String token = "owzdntuxaycwigdxykntmleupp";
        String aeskey= "oidyqp17u4syhmwhf8e6yyramlkqesopti7g5qud5nb";
        String appid = "wx2fb98bf98531eaba";
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, aeskey, appid);
        String xml = pc.decryptMsg(msg_signature, timestamp, nonce, postData);
        System.out.println(xml);
        Map<String, Object> xml2Map = XmlUtils.xml2Map(xml);
        System.out.println(xml2Map);

        return "success";
    }
}
